package com.gxa.eshop.admin.utils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Map;

public class HttpClientUtil {

    private static RestTemplate restTemplate = new RestTemplate();

    public static Object postWithParam(String uriString,  MultiValueMap<String, Object> paramMap,Class clazz) throws Exception {
        URI uri = new URI(uriString);
        Object o = restTemplate.postForObject(uri, paramMap, clazz);
        //System.out.println(result);
        return o;
    }

    public  static Object postWithoutParam(String uriString,Class clazz) throws Exception {
        // 使用Spring自己的RestTemplate
        return postWithParam(uriString,null,clazz);
    }

    public  static Object postWithForm(String uriString, MultiValueMap<String, Object> paramMap,Class clazz) throws Exception {
        // 使用Spring自己的RestTemplate
        URI uri = new URI(uriString);
        Object o = restTemplate.postForObject(uri, paramMap, clazz);
        //System.out.println(result);
        return o;
    }

    public  static Object postWithBody(String uriString,HttpHeaders httpHeaders, Map<String, Object> param, Class clazz) throws Exception {
        // 使用Spring自己的RestTemplate
        URI uri = new URI(uriString);
        //header
//        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity<Map<String, Object>> httpEntity = new HttpEntity<>(param,httpHeaders);
        Object o = restTemplate.postForObject(uri, httpEntity, clazz);
        return o;
    }
}